package io.kiki.sba.registry.common.model.dataserver;


import io.kiki.sba.registry.common.model.RegisterVersion;
import io.kiki.sba.registry.common.model.slot.filter.SyncAcceptorRequest;
import io.kiki.sba.registry.common.model.slot.filter.SyncSlotAcceptorManager;
import io.kiki.sba.registry.common.model.store.Publisher;
import lombok.Getter;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


@Getter
public class DatumSummary implements Serializable {

    private final String dataInfoId;

    private final Map<String /*registerId*/, RegisterVersion> registerIdToRegisterVersionMap;

    public DatumSummary(String dataInfoId, Map<String /*registerId*/, RegisterVersion> registerIdToRegisterVersionMap) {
        this.dataInfoId = dataInfoId;
        this.registerIdToRegisterVersionMap = registerIdToRegisterVersionMap;
    }

    public DatumSummary(String dataInfoId) {
        this.dataInfoId = dataInfoId;
        this.registerIdToRegisterVersionMap = new HashMap<>();
    }

    public static DatumSummary of(String dataInfoId, Map<String, Publisher> registerIdToPublisherMap, SyncSlotAcceptorManager acceptorManager) {
        Map<String, RegisterVersion> registerIdToRegisterVersionMap = new HashMap<>(registerIdToPublisherMap.size());
        for (Map.Entry<String, Publisher> entry : registerIdToPublisherMap.entrySet()) {
            // filter publisher
            if (!acceptorManager.accept(SyncAcceptorRequest.buildRequest(dataInfoId, entry.getValue().getPublishSource()))) {
                continue;
            }

            registerIdToRegisterVersionMap.put(entry.getKey(), entry.getValue().registerVersion());
        }
        return new DatumSummary(dataInfoId, registerIdToRegisterVersionMap);
    }

    public static int countPublisherSize(Collection<DatumSummary> collection) {
        int count = 0;
        for (DatumSummary datumSummary : collection) {
            count += datumSummary.size();
        }
        return count;
    }

    public Map<String, RegisterVersion> getRegisterIdToRegisterVersionMap(Collection<String> registerIds) {
        Map<String, RegisterVersion> map = new HashMap<>(registerIds.size());
        for (String registerId : registerIds) {
            RegisterVersion registerVersion = registerIdToRegisterVersionMap.get(registerId);
            if (registerVersion == null) {
                throw new IllegalArgumentException("not contains registerId:" + registerId);
            }
            map.put(registerId, registerVersion);
        }
        return map;
    }

    public boolean isEmpty() {
        return registerIdToRegisterVersionMap.isEmpty();
    }

    public int size() {
        return registerIdToRegisterVersionMap.size();
    }


}
